<template>
  <section>
    <el-row>
      <el-col class="header" :span="21">
        <div class="title">
          <span>商品管理</span>
        </div>
      </el-col>
    </el-row>
    <!-- ------------- -->
    <el-row>
      <el-col class="quescard" :span="21">
        <el-card>
          <el-row class="card" :gutter="20">
            <el-col :span="7">
              <search-box
                @inputChange="inputChange"
                @searchClick="searchClick"
                placeholder="搜索商品"
              ></search-box>
            </el-col>
            <el-col :span="2">
              <el-button class="addButton" type="primary" @click="addShopDrawer"
                >添加商品</el-button
              ></el-col
            >
          </el-row>

          <!-- 商品列表信息 -->
          <el-table :data="commodityList" border stripe>
            <el-table-column type="index"> </el-table-column>
            <el-table-column prop="title" label="花名"> </el-table-column>
            <el-table-column prop="flower_language" label="花语">
            </el-table-column>
            <el-table-column prop="price" label="价格"> </el-table-column>
            <el-table-column prop="desc" label="鲜花描述"> </el-table-column>
            <el-table-column label="图片">
              <template v-slot="scope">
                <img
                  class="picture"
                  :src="item"
                  v-for="(item, index) in scope.row.image"
                  :key="index"
                  alt="图片失效"
                />
              </template>
            </el-table-column>
            <el-table-column prop="type_id" label="分类">
              <!-- <template v-slot="scope">
                {{ requestUtil.getGueryTypeNameById(scope.row.type_id) }}
              </template> -->
            </el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="updateShop(scope)"
                ></el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteShop(scope)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 抽屉容器 -->
    <el-drawer
      :before-close="drawerClose"
      title="添加商品"
      :visible.sync="drawer"
      size="40%"
    >
      <el-form
        label-width="80px"
        :model="addShopDate"
        :rules="rules"
        ref="addShopRef"
      >
        <el-form-item label="花名:" prop="title">
          <el-input v-model="addShopDate.title"></el-input>
        </el-form-item>
        <el-form-item label="描述:" prop="desc">
          <el-input type="textarea" v-model="addShopDate.desc"></el-input>
        </el-form-item>
        <el-form-item label="花语:" prop="flower_language">
          <el-input
            type="textarea"
            v-model="addShopDate.flower_language"
          ></el-input>
        </el-form-item>
        <el-form-item label="价格:">
          <div class="inputNumber">
            <el-input-number
              v-model="addShopDate.price"
              :min="1"
              :max="10000"
              label="描述文字"
            ></el-input-number>
          </div>
        </el-form-item>
        <el-form-item label="图片:">
          <div class="upload">
            <el-upload
              ref="upload"
              :on-success="handle_success"
              action="http://localhost:8081/api/upload"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :headers="headerObj"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
          </div>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
        </el-form-item>
        <el-form-item label="分类:">
          <div class="type">
            <el-select v-model="addShopDate.type_id" placeholder="请选择">
              <el-option
                v-for="item in typeList"
                :key="item.id"
                :label="item.type_name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button class="submit" type="primary" @click="addShop"
            >提交</el-button
          ><el-button class="reset" type="info" @click="resetShop"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </el-drawer>

    <!-- 修改商品容器 -->
    <el-drawer
      :before-close="updateDrawerClose"
      title="修改商品"
      :visible.sync="updateDrawer"
      size="40%"
    >
      <el-form
        label-width="80px"
        :model="updateDate.data"
        :rules="rules"
        ref="addShopRef"
      >
        <el-form-item label="花名:" prop="title">
          <el-input v-model="updateDate.data.title"></el-input>
        </el-form-item>
        <el-form-item label="描述:" prop="desc">
          <el-input type="textarea" v-model="updateDate.data.desc"></el-input>
        </el-form-item>
        <el-form-item label="花语:" prop="flower_language">
          <el-input
            type="textarea"
            v-model="updateDate.data.flower_language"
          ></el-input>
        </el-form-item>
        <el-form-item label="价格:">
          <div class="inputNumber">
            <el-input-number
              v-model="updateDate.data.price"
              :min="1"
              :max="10000"
              label="描述文字"
            ></el-input-number>
          </div>
        </el-form-item>
        <el-form-item label="图片:">
          <span style="color: red">图片无法修改</span>
        </el-form-item>
        <el-form-item label="分类:">
          <div class="type">
            <el-select v-model="updateDate.data.type_id" placeholder="请选择">
              <el-option
                v-for="item in typeList"
                :key="item.id"
                :label="item.type_name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button class="submit" type="primary" @click="submintUpdateShop"
            >提交修改</el-button
          >
        </el-form-item>
      </el-form>
    </el-drawer>
  </section>
</template>
<script>
import { $http } from "../../request/service";

import SearchBox from "components/toolAssembly/SearchBox";

export default {
  name: "QuestionnaireList",
  data() {
    return {
      str: "",
      headerObj: {
        token: window.sessionStorage.getItem("token"),
      },
      dialogImageUrl: "",
      dialogVisible: false,
      // ---------------------
      drawer: false,
      commodityList: [],
      // 添加商品数据
      addShopDate: {
        title: "",
        desc: "",
        flower_language: "",
        price: 0,
        image: "",
        type_id: "请选择分类",
      },
      // 修改商品数据表单
      updateDate: {
        id: 0,
        data: {
          title: "",
          desc: "",
          flower_language: "",
          price: 0,
          image: "",
          type_id: "请选择分类",
        },
      },
      deleteImgData: [],
      imgArr: [],
      // 分类列表
      typeList: [],
      // 定义表单校验规则
      rules: {
        title: [{ required: true, message: "请输入花的名称", trigger: "blur" }],
        desc: [
          { required: true, message: "请输入对花的描述", trigger: "blur" },
        ],
        flower_language: [
          { required: true, message: "请输入花语", trigger: "blur" },
        ],
      },
      // 修改容器
      updateDrawer: false,
    };
  },
  components: { SearchBox },
  created() {
    this.getShopList();
  },
  computed: {
    // _imgArr() {
    //   return this.imgArr.toString();
    // }
  },
  mounted() {},
  methods: {
    // 搜索商品功能
    searchClick(value) {
      $http.get(`/queryCommodity?name=${value}`).then((res) => {
        res.data.filter((item) => {
          item.image = item.image.split(",");
        });
        this.commodityList = res.data;
      });
    },
    inputChange(blo) {
      if (blo) return this.getShopList();
    },
    // 提交修改
    submintUpdateShop() {
      $http
        .put(`/commodity/${this.updateDate.id}`, this.updateDate.data)
        .then((res) => {
          if (res.code !== 200) return this.$message.error(res.data.msg);

          this.$message.success(res.data.msg);
          this.updateDrawer = false;
          this.getShopList();
        });
    },
    // 点击显示修改容器
    updateShop(scope) {
      this.updateDrawer = true;

      this.getTypeList();
      this.updateDate.id = scope.row.id;
      this.updateDate.data.image = scope.row.image.toString();
      this.updateDate.data.desc = scope.row.desc;
      this.updateDate.data.flower_language = scope.row.flower_language;
      this.updateDate.data.price = scope.row.price;
      this.updateDate.data.title = scope.row.title;
      this.updateDate.data.type_id = scope.row.type_id;
    },
    // 关闭修改抽屉对话框
    updateDrawerClose() {
      this.updateDrawer = false;
    },
    // 关闭抽屉
    drawerClose() {
      this.resetShop();
      this.drawer = false;
    },
    // 删除商品
    deleteShop(scope) {
      this.deleteImgData = [];
      console.log(scope);
      scope.row.image.filter((item) => {
        let imgurl = {};
        this.deleteImgData.push((imgurl.imgUrl = item.substring(21)));
      });

      this.$confirm("此操作将永久删除该商品, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          $http
            .delete(`/commodity/${scope.row.id}`, this.deleteImgData)
            .then((res) => {
              if (res.code !== 200) return this.$message.error(res.data.msg);

              this.$message.success("删除成功");
              this.getShopList();
            });
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
    // 获取分类列表
    getTypeList() {
      $http.get("/comtype").then((res) => {
        if (res.code !== 200) return this.$message.error(res.data.msg);
        this.typeList = res.data;
      });
    },
    // 重置表单
    resetShop() {
      this.$refs.addShopRef.resetFields();
      this.$refs.upload.clearFiles();
      this.addShopDate.image = "";
      // this.deleteImgData = [];
      // this.imgArr.filter(item => {
      //   let imgurl = {};
      //   this.deleteImgData.push((imgurl.imgUrl = item.substring(21)));
      // });
      $http.post("/deleteImgArr", this.deleteImgData);
      this.imgArr = [];
    },
    // 录入商品
    addShop() {
      this.$refs.addShopRef.validate(async (valid) => {
        if (!valid) return;
        if (typeof this.addShopDate.type_id == "string")
          return this.$message.error("请选择分类");
        $http.post("/commodity", this.addShopDate).then((res) => {
          console.log(res);
          if (res.data.msg !== "添加成功")
            return this.$message.error(res.data.msg);
          this.$message.success(res.data.msg);
          this.resetShop();
          this.getShopList();
        });
      });
    },

    // 图片上传功能
    handle_success(e) {
      console.log(e.msg.url);
      if (e.code !== 200) return this.$message.error("上传失败");
      this.$message.success("上传成功");
      this.imgArr.push("http://127.0.0.1:7001" + e.msg.url);
      this.addShopDate.image = this.imgArr.join(",");
    },
    // 删除图片功能
    deleteImg(file) {
      $http
        .post("/deleteImg", { imgUrl: file.__ob__.value.response.msg.url })
        .then((res) => {
          console.log(res);
          if (res.code == !200) return this.$message.error("删除失败");
          this.$message.success(res.msg);

          let arr = this.imgArr.filter((item) => {
            return item !== "http://127.0.0.1:7001" + res.imgUrl;
          });
          this.imgArr = arr;
          this.addShopDate.image = this.imgArr.join(",");
          console.log(arr, "shuj");
        })
        .catch((error) => {
          console.log(error);
        });
    },
    handleRemove(file) {
      console.log(file.__ob__.value.response.msg.url);
      this.deleteImg(file);
    },
    handlePictureCardPreview(file) {
      console.log(file);
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // ------------------------------------------------

    // 打开抽屉
    addShopDrawer() {
      this.drawer = true;
      // 获取分类列表
      this.getTypeList();
    },

    // 获取商品列表
    getShopList() {
      $http.get("/commodity").then((res) => {
        if (res.code !== 200) return this.$message.error(res.data.msg);
        res.data.filter((item) => {
          item.image = item.image.split(",");
        });
        this.commodityList = res.data;
      });
    },
  },
};
</script>
<style scoped>
.picture {
  width: 40px;
  height: 40px;
  margin-left: 4px;
}
.reset {
  width: 100%;
  margin-top: 10px;
  margin-left: 0;
}
.submit {
  width: 100%;
  margin-top: 150px;
}
.type {
  display: flex;
  justify-content: flex-start;
}
.inputNumber,
.upload {
  display: flex;
  justify-content: flex-start;
}
.upload {
  border: 1px solid #dcdfe6;
}
.el-form {
  margin: 40px;
}
.addButton {
  border-radius: 30px;
  background-color: #fc5d5d;
  border: 1px solid #fc5d5d;
  height: 48px;
}
.card {
  padding: 0 !important;
}

.header {
  display: flex;
  align-content: center;
  justify-content: space-between;
}
.el-table {
  margin-top: 20px;
}
.el-row {
  padding-top: 50px;
  display: flex;
  align-items: center;
}
.title {
  display: flex;
  align-items: center;
  text-align: start;
  font-size: 20px;
  font-weight: 700;
}
.searchWai {
  padding-left: 260px;
}
</style>
